package com.moyu.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moyu.admin.bean.TreeNodePerm;
import com.moyu.admin.service.ISysPermissionService;
import com.moyu.data.dao.SysPermissionMapper;
import com.moyu.data.domain.SysPermission;
import com.moyu.data.domain.SysRole;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 服务实现类
 *
 * @author makun
 * @since 2019-02-22
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
    implements ISysPermissionService {
  @Autowired private SysPermissionMapper sysPermissionMapper;

  @Override
  public List<SysPermission> findPermissionsByRoles(List<SysRole> roles) {
    return sysPermissionMapper.findPermissionByRoles(roles);
  }

  @Override
  public List<TreeNodePerm> listNodes() {
    List<TreeNodePerm> result = getByPid(null);
    for (TreeNodePerm node : result) {
      node.setNodes(getByPid(node.getPkId()));
    }
    return result;
  }

  @Override
  public List<Long> listByRoleId(Long roleId) {
    return sysPermissionMapper.findPermissionIdByRoleId(roleId);
  }

  private List<TreeNodePerm> getByPid(Long pid) {
    List<TreeNodePerm> result = new ArrayList<>();
    QueryWrapper<SysPermission> qw = new QueryWrapper<>();
    if (pid == null) {
      qw.isNull("pid");
    } else {
      qw.eq("pid", pid);
    }
    list(qw).forEach(obj -> result.add(new TreeNodePerm(obj.getId(), obj.getPermissionName())));
    return result;
  }
}
